require 'net/http'
require 'net/https'
#http://ditrader.di.se/DiTrader/DITraderAFS.aspx?Page=http:%2f%2fdi.se%2flogin%2flogin_trader.aspx%3fP%3d4%26DoLogin%3dY
#http://ditrader.di.se/DiTrader/DITraderAFS.aspx?Page=http:%2f%2fdi.se%2flogin%2flogin_trader.aspx%3fP%3d4%26DoLogin%3dY
path='/login/login_trader.aspx?P=4&DoLogin=Y'

http = Net::HTTP.new('di.se', 80)
#http.use_ssl = true


# GET request -> so the host can set his cookies
puts "GET request"
resp, data = http.get(path, nil)
puts '---------------------------------------------------------------------'
cookie = resp.response['set-cookie']


# POST request -> logging in
puts "POST request"
pathLogin='/login/login_trader.aspx'

data = 'DITName=##&DITPSW=##&InSubmit=Y&AddID=&P=4&AddItW=&AddItP='
headers = {
  'Cookie' => cookie,
  'Referer' => 'http://di.se/login/login_trader.aspx?P=4&DoLogin=Y',
  'Content-Type' => 'application/x-www-form-urlencoded',
  'User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; sv-SE; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1'
}

resp, data = http.post(pathLogin, data, headers)

#follow the redirect
httptrader = Net::HTTP.new('ditrader.di.se', 80)
cookie = resp.response['set-cookie']
location = resp.response['location'].gsub!(/http:\/\/ditrader\.di\.se/, "")
puts "FOLLOWING REDIECT " + location
headers = {
  'Cookie' => cookie,
  'Referer' => 'http://di.se/login/login_trader.aspx?P=4&DoLogin=Y',
  'Connection' => 'keep-alive',
  'User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; sv-SE; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1'
}
resp = httptrader.get(location, headers)

#another redirect
httpportfolio = Net::HTTP.new('portfolio.di.se', 80)
cookie = resp.response['set-cookie']
location = '/showportfolio.aspx?portfolioId=200527'
puts "FOLLOWING REDIECT " + location
headers = {
  'Cookie' => 'PortfolioSession=askmera%7caskmera%40gmail.com%7c2007-01-11+22%3a01%3a32%7cBHQ5txCzgHUmw5wI0JVdBQ%3d%3d; ASP.NET_SessionId=sjmkw333smym1x45hlxvlzfs; ecovisionSession=119554681',
  'Referer' => 'http://di.se/login/login_trader.aspx?P=4&DoLogin=Y',
  'Connection' => 'keep-alive',
  'User-Agent' => 'Mozilla/5.0 (Windows; U; Windows NT 5.1; sv-SE; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1'
}
resp = httpportfolio.get(location, headers)




# Output on the screen -> we should get either a 302 redirect (after a successful login) or an error page
puts 'Code = ' + resp.code
puts 'Message = ' + resp.message
resp.each {|key, val| puts key + ' = ' + val}
puts data


